import { defineStore } from 'pinia'
import { exchangeSm2Api } from '@/request/api/user'
import type { PageVO, ResultType } from '@/type/type'
import { getResourcesPageApi, type ResourcesVO } from '@/request/api/resources'
import default_img from '@/assets/img/default.webp'
import type { DialogType, SystemType } from '@/type'
import { DialogEnum } from '@/enum'
import { browserName, browserVersion, osName, osVersion } from 'vue-device-detect'

// 非持久化
export const useSystemStore = defineStore(
  'system',
  () => {
    // 系统信息
    const system = ref<SystemType>({
      isLeave: false,
      isOpenLenis: false,
      isOpenClick: true,
      routeMap: new Map<string, string>(),
      resources: [],
      isShowMobile: false,
      isLt1024: false,
      isLt768: false,
      browserName: browserName,
      browserVersion: browserVersion,
      osName: osName,
      osVersion: osVersion
    })

    window.addEventListener('resize', () => {
      const w = document.documentElement.clientWidth
      system.value.isLt1024 = w < 1024
      system.value.isLt768 = w < 768

      if (w > 1024) {
        system.value.isShowMobile = false
      }
    })

    // 系统弹窗状态管理
    const dialog = ref<{ [key in DialogType]: boolean }>({
      [DialogEnum.SEARCH]: false,
      [DialogEnum.SETTING]: false,
      [DialogEnum.ROUTER]: false,
      [DialogEnum.RESOURCES]: false,
      [DialogEnum.CLASSIFY]: false,
      [DialogEnum.LABEL]: false,
      [DialogEnum.USER]: false,
      [DialogEnum.ALBUM]: false,
      [DialogEnum.ROLE]: false,
      [DialogEnum.ARTICLE]: false,
      [DialogEnum.COMMENT]: false,
      [DialogEnum.FRIENDS]: false,
      [DialogEnum.TREE_HOLE]: false
    })

    // 系统图片预览
    const imgPreview = ref<{ imgUrl: string }>({
      imgUrl: ''
    })

    // 后端sm2公钥
    const backendSm2 = ref<{ publicKey: string }>({
      publicKey: ''
    })

    const getRandomImg = () => {
      if (system.value.resources.length === 0) {
        return default_img
      }
      const random = Math.floor(Math.random() * system.value.resources.length)
      return system.value.resources[random].url
    }

    return {
      system,
      dialog,
      imgPreview,
      backendSm2,
      getRandomImg
    }
  },
  {
    persist: {
      paths: ['system.isOpenLenis', 'system.isOpenClick'],
      afterRestore: ({ store }) => {
        exchangeSm2Api().then((res: ResultType<string>) => {
          store.backendSm2.publicKey = res.data
        })

        getResourcesPageApi({
          size: 50,
          current: 1,
          param: {
            labelId: 83,
            status: true
          }
        }).then((res: ResultType<PageVO<ResourcesVO>>) => {
          store.system.resources = res.data.list
        })
      }
    }
  }
)
